package com.chuji.crmcj.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by w.pitt on 2016/1/19.
 */
public class RecordService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static CallBackInterface mCallBackInterface;

    //定义接口.且在接口中定义一个方法
    public interface CallBackInterface {
        public void callBackFunction();
    }

    //设置回调接口(监听器)的方法
    public void showDialog(CallBackInterface callBackInterface) {
        mCallBackInterface = callBackInterface;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//		Intent intent=new Intent();
        //电话管理
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);

        telephonyManager.listen(new MyphoneListener(), PhoneStateListener.LISTEN_CALL_STATE);

        System.out.println("通话服务开启...");
    }

    class MyphoneListener extends PhoneStateListener {
        //media   录音机
        MediaRecorder mediaRecorder;

        boolean isCall = false;

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch (state) {
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    System.out.println("通话前准备");
                    isCall = true;
                    //新建一个录音机
                    mediaRecorder = new MediaRecorder();
                    //设置录音格式
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    //设置输出格式
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    //格式化日期 作为文件的名字
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = new Date();

                    String fileName = format.format(date);
//                    mediaRecorder.setOutputFile("/sdcard/myRecord/" + fileName + ".3gp");
                    mediaRecorder.setOutputFile(getFilesDir() + "/" + fileName + ".mp3");
//                    SPUtils.saveString(UIUtils.getContext(), "Record", "/sdcard/myRecord/" + fileName + ".3gp");
                    SPUtils.saveString(UIUtils.getContext(), "Record", getFilesDir() + "/" + fileName + ".3gp");
                    //设置音频
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                    try {
                        //录音准备
                        mediaRecorder.prepare();
                        //录音开始
                        mediaRecorder.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (isCall) {
                        mCallBackInterface.callBackFunction();
                        if (mediaRecorder != null) {
                            try {
                                //下面三个参数必须加，不加的话会奔溃，在mediarecorder.stop();
                                //报错为：RuntimeException:stop failed
                                mediaRecorder.setOnErrorListener(null);
                                mediaRecorder.setOnInfoListener(null);
                                mediaRecorder.setPreviewDisplay(null);
                                mediaRecorder.stop();
                            } catch (IllegalStateException e) {
                                // TODO: handle exception
                                Log.i("Exception1", Log.getStackTraceString(e));
                            } catch (RuntimeException e) {
                                // TODO: handle exception
                                Log.i("Exception2", Log.getStackTraceString(e));
                                // 录音的时候因为音频小于1s报错  MediaRecorder录制视频太短崩的问题
                                UIUtils.showToastSafe("录音的时候因为音频小于1s报错  MediaRecorder录制视频太短崩的问题");
                            } catch (Exception e) {
                                // TODO: handle exception
                                Log.i("Exception3", Log.getStackTraceString(e));
                            }
                            mediaRecorder.reset();
                            mediaRecorder.release();
                            mediaRecorder = null;
                            isCall = false;
                            System.out.println("录音结束");
                            break;
//                    mediaRecorder.setOnErrorListener(null);
//                    mediaRecorder.setOnInfoListener(null);
//                    mediaRecorder.setPreviewDisplay(null);
//                    mediaRecorder.stop();
//                    mediaRecorder.release();
//                    isCall = false;
//                    System.out.println("录音结束");
                        }
                    }
            }
        }
    }
}